//
//  ZYSubAccountListVC.m
//  YiLin
//
//  Created by Zyark on 2018/6/1.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYSubAccountListVC.h"
#import "ZYUser.h"
#import "ZYSubAccountViewCell.h"
#import "ZYModifySubAccountVC.h"
#import "ZYImageUtils.h"
#import "ZYSubAccountViewModel.h"

#define kAccountCellItemID  @"account_cell_item"
@interface  ZYSubAccountListVC()<UITableViewDelegate,UITableViewDataSource,ZYSubAccountViewCellDelegate>
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) UIButton *addButton;
@property(nonatomic,strong) NSMutableArray<ZYUser *> *accountArray;
@property(nonatomic,strong) ZYSubAccountViewModel *viewModel;
@property(nonatomic,strong) ZYUser *user;
/**
 数据量
 */
@property(nonatomic,assign) NSInteger count;
@end

@implementation ZYSubAccountListVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ME_MAIN_SUBACCOUNT_LIST];
    [self.viewModel loadNewSubAccountList];
}

#pragma mark -init
-(void)setup{
    [self setupAddButton];
    [self setupTableView];
    [self setupBindTableView];
}

-(void)setupTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H - self.navigationView.height - _addButton.height -1 - SafeAreaBottomHeight)];
    [self.view addSubview:_tableView];
    _tableView.top = self.navigationView.bottom;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[ZYSubAccountViewCell class] forCellReuseIdentifier:kAccountCellItemID];
    NSLog(@"%lu",(unsigned long)self.accountArray.count);
    [_tableView reloadData];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

//绑定表格刷新操作
-(void)setupBindTableView{
    @weakify(self);
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        self.count = 0;
        [self.viewModel loadNewSubAccountList];
    }];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        [self.viewModel loadMoreSubAccountList];
    }];
    [[[self.viewModel.sourceCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.accountArray = x;
        if([x count] == self.count){
            self.tableView.mj_footer.hidden = YES;
        }
        self.count = [x count];
        [self.tableView reloadData];
    }];
    [self.viewModel.sourceCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        if([[NSErrorHelper handleErrorMessage:x] isEqualToString:LOGIN_FAILURE]){
            //登录失效
            [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
        }
    }];
    [self.viewModel.sourceCommand.executing subscribeNext:^(id isExcuting) {
        @strongify(self);
        if (![isExcuting boolValue]) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
    }];
    
    [self.viewModel.deleteCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        [self.accountArray removeObject:self.user];
        [self.tableView reloadData];
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_DELETE_SUB_ACCOUNT_SUCCESS]];
    }];
    [self.viewModel.deleteCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
    }];
    //监听状态
    [[self.viewModel.deleteCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
}

-(void)setupAddButton{
    _addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, 50)];
    NSString *title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ME_MAIN_ADD_SUBACCOUNT_TITLE];
    title = [NSString stringWithFormat:@"%@%@",@"+",title];
    [_addButton setTitle:title forState:UIControlStateNormal];
    [_addButton setTitleColor:kMainColor forState:UIControlStateNormal];
    [_addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_addButton setBackgroundImage:[ZYImageUtils imageWithColor:kMainColor rect:_addButton.bounds] forState:UIControlStateHighlighted];
    [self.view addSubview:_addButton];
    NSLog(@"SafeAreaBottomHeight:%.0f",self.view.bottom - SafeAreaBottomHeight);
    _addButton.bottom = self.view.bottom - SafeAreaBottomHeight;
    [_addButton addTarget:self action:@selector(addSubAccount) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, 1)];
    line.backgroundColor = RGBA(235, 235, 235, 1);
    [self.view addSubview:line];
    line.bottom = _addButton.top;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.accountArray.count;
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [tableView fd_heightForCellWithIdentifier:kCommentCellID cacheByIndexPath:indexPath configuration:^(PBSCommentTableCell *  cell) {
//        //        cell.fd_enforceFrameLayout = NO;
//        cell.comment = self.commentArray[indexPath.row];
//    }];
//}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZYSubAccountViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kAccountCellItemID];
    // 判断为空进行初始化  --（当拉动页面显示超过主页面内容的时候就会重用之前的cell，而不会再次初始化）
    if (!cell) {
        cell = [[ZYSubAccountViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kAccountCellItemID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    ZYUser *account = self.accountArray[indexPath.row];
    cell.account = account;
    return cell;
}

#pragma mark ZYSubAccountViewCellDelegate
-(void)subAccountViewCell:(ZYSubAccountViewCell *)subAccountViewCell doDelete:(ZYUser *)account{
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[language getStringByKey:LC_DELETE_SUB_ACCOUNT_HINT] message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    @weakify(self)
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_ALERT_CONTER_BTN_CONFIRM] style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.user = account;
        [self.viewModel deleteSubAccount:[NSString stringWithFormat:@"%ld",(long)account.userId]];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_ALERT_CONTER_BTN_CANCEL] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        return;
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

-(void)subAccountViewCell:(ZYSubAccountViewCell *)subAccountViewCell doEdit:(ZYUser *)account{
    ZYModifySubAccountVC *vc = [[ZYModifySubAccountVC alloc] init];
    vc.type = ZYModifySubAccountTypeEdit;
    vc.account = account;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Event
-(void)addSubAccount{
    ZYModifySubAccountVC *vc = [[ZYModifySubAccountVC alloc] init];
    vc.type = ZYModifySubAccountTypeAdd;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -Getter
-(ZYSubAccountViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYSubAccountViewModel alloc] init];
    }
    return _viewModel;
}
@end
